#include "TcpServer.hpp"
#include <memory>
#include <iostream>

using namespace std;

extern Log lg;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n" << std::endl;
}

// ./tcpclient serverip serverport
int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        cout << "socker error" << endl;
        return 1;
    }
    lg(Info, "socket create success, sockfd: %d", sockfd);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    // inet_pton 中 p -> process, n -> net 意为将本地的东西转换为网络的东西
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    //tcp客户端要不要bind?——要的，那要不要显示的bind?——不需要，系统使用随机端口进行bind
    //客户端发起connect的时候,进行自动随机bind

    // connect 类似于sendto
    int n = connect(sockfd, (struct sockaddr*)&server, sizeof(server));
    if(n < 0)
    {
        std::cerr << "connect error. . ." << std::endl;
        return 2;
    }

    std::string message;
    while(true)
    {
        std::cout << "Please Enter: ";
        std::getline(std::cin, message);

        write(sockfd, message.c_str(), message.size());
        
        char inbuffer[4096];
        int n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
    }

    close(sockfd);
    return 0;
}